import { getDB } from '../db/connection.js';

class GrayRelease {
  static async getAll() {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM gray_releases');
    return rows;
  }

  static async getById(id) {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM gray_releases WHERE id = ?', [id]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async getByComponentVersionId(componentVersionId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM gray_releases WHERE component_version_id = ?',
      [componentVersionId]
    );
    return rows;
  }

  static async getActiveReleases() {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM gray_releases WHERE status = ?',
      ['active']
    );
    return rows;
  }

  static async create(componentVersionId, threshold, percentage = 100.00, status = 'pending') {
    const db = await getDB();
    const [result] = await db.execute(
      'INSERT INTO gray_releases (component_version_id, threshold, percentage, status) VALUES (?, ?, ?, ?)',
      [componentVersionId, threshold, percentage, status]
    );
    return result.insertId;
  }

  static async update(id, data) {
    const db = await getDB();
    const fields = Object.keys(data);
    const values = Object.values(data);
    const setClause = fields.map(field => `${field} = ?`).join(', ');
    
    await db.execute(
      `UPDATE gray_releases SET ${setClause} WHERE id = ?`,
      [...values, id]
    );
    
    return this.getById(id);
  }

  static async activate(id) {
    const db = await getDB();
    await db.execute(
      'UPDATE gray_releases SET status = ?, start_time = NOW() WHERE id = ?',
      ['active', id]
    );
    return this.getById(id);
  }

  static async complete(id) {
    const db = await getDB();
    await db.execute(
      'UPDATE gray_releases SET status = ?, end_time = NOW() WHERE id = ?',
      ['completed', id]
    );
    return this.getById(id);
  }

  static async pause(id) {
    const db = await getDB();
    await db.execute(
      'UPDATE gray_releases SET status = ? WHERE id = ?',
      ['paused', id]
    );
    return this.getById(id);
  }

  static async delete(id) {
    const db = await getDB();
    await db.execute('DELETE FROM gray_releases WHERE id = ?', [id]);
  }
}

export default GrayRelease;
